<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Remote File Transfer Class
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	Downloads
 * @version		1.2
 * @author		Matthew Glinski
 * @link		---- Not Yet Documented or Hosted ----
 */
 
class CI_Remotefile
{
	public $buffer = 4096;
	public $tmp_dir = '/tmp';

	/**
	 * File Download Constructor
	 *
	 * The constructor sets up the download system as ready for files
	 */		
	function CI_Remotefile()
	{
		$this->CI =& get_instance();
		log_message('debug', "Remote File Transfer Class Initialized");
	}
	
	/**
	 * Setup
	 *
	 * Sets Config Vars
	 *
	 * @access	public
	 * @param	Config Array
	 * @return	null
	 */
	 function setup($config = array())
	 {
	 	if (count($config) > 0)
		{
			$this->_initialize($config);
		}
	 }
	 
	 function remoteSize($url)
	 {
	 	$headers = get_headers($url, true);
		return $headers['Content-Length'];
	 }
	 
	 function fetchFile($url, $fp=NULL)
	 {
	 	// Open the remote file connection
	 	$fpurl = fopen($url, 'rb');
		if(!$fpurl)
		{
			return false;
		}
		
		// if no filepointer is given, make a temp file open it for writing
		if(!$fp)
		{
			$sendFileName = true;
			$tmpfname = tempnam($this->tmp_dir, "RFT-");
			$fp = fopen($tmpfname, "wb");
		}
		
		// download the file
		while(!feof($fpurl))
		{
			$string = fread($fpurl, $buffer);
			fwrite($fp, $string);
			$string = NULL;
		}
		fclose($fpurl);
		fclose($fp);
		
		// if passed a file pointer return true, if not return temp file name
		if(!$sendFileName)
		{
			return true;
		}
		else
		{
			return $tmpfname;
		}
	 }
}
?>